package com.lxkpt.controller;

import com.lxkpt.bean.User;
import com.lxkpt.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Resource
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    /**
     * 登录
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(User user) {

        Map<Object, Object> map = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getUserPassword());
        try {
            subject.login(token);
            Session session = subject.getSession();
            User u = new User();
            u.setUserName(user.getUserName());
            User currentUser = userService.selectOneUser(u);
            session.setAttribute("currentUser", currentUser);
            map.put("message", "success");

        } catch (DisabledAccountException e) {
            map.put("message", "您不是管理员，没有登录权限");
        } catch (UnknownAccountException e) {
            map.put("message", "您输入的账户不存在");
        } catch (IncorrectCredentialsException e) {
            map.put("message", "您输入的密码错误");
        }
        return map;
    }
}
